package com.example.compose.utils

import android.graphics.Bitmap
import android.os.Environment
import android.os.Environment.DIRECTORY_PICTURES
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class BitmapUtils {

    fun saveToLocalPNG(bm: Bitmap): File? {

        val appDir: File = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES)//App().getContext().getExternalFilesDir(DIRECTORY_PICTURES)!!
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
            return null
        }
        var fileOutputStream: FileOutputStream? = null
        val fileName = System.currentTimeMillis().toString() + ".png"
        val filePath = "$appDir/$fileName"
        val f = File(filePath)
        if (!f.exists()) {
            try {
                f.createNewFile()
                fileOutputStream = FileOutputStream(filePath)
                bm.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush()
                        fileOutputStream.close()
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        } else {
            try {
                f.delete()
                fileOutputStream = FileOutputStream(filePath)
                bm.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    fileOutputStream!!.flush()
                    fileOutputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }

        return f
    }
}